/*
 * Created on Dec 24, 2003
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.vandagroup.portal;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.vandagroup.common.bo.UserContext;

import com.vandagroup.common.resources.SysPara;
import com.vandagroup.common.util.Paras;
import com.vandagroup.common.util.StringUtility;
import com.vandagroup.common.util.web.WebSelUtil;
import com.vandagroup.common.webapp.ActiveAction;
import com.vandagroup.common.webapp.AppLoginInterface;
//import com.vandagroup.common.webapp.PCSUtil;
import com.vandagroup.common.webapp.ResourceReader;

//import com.vandagroup.pcs.sysmanage.datacontrast.C_zxxt_dmdzbBO;
//import com.vandagroup.pcs.sysmanage.datacontrast.C_zxxt_dmdzbFormBean;
import com.vandagroup.portal.oper.OperBO;
import com.vandagroup.portal.oper.OperFormBean;
import com.vandagroup.portal.org.OrgBO;
import com.vandagroup.portal.org.OrgFormBean;

/**
 * @author ERIC LEE
 * 
 * To change the template for this generated type comment go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
public class LoginAction extends ActiveAction {

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response,
			UserContext user) throws Exception {
		try {
			LoginForm loginForm = (LoginForm) form;
			String loginID = loginForm.getLoginID();
			String password = loginForm.getPassword();
			boolean bValid = false;
			int errorTimes = 0;
			String loginType = loginForm.getOperType();
			String operType = null;

			OperBO bo = new OperBO();
			operType = bo.getLoginType(loginID, password); //首先判斷用戶、密碼是否存在

			if (operType != null)
				bValid = true;
			else
				bValid = false;
			if (operType != null && !operType.equals(loginType)) { //用戶名密碼正確，用戶類型錯誤
				ActionErrors errors = new ActionErrors();
				return (forwardErrorPage(request, mapping, ResourceReader
						.getMessageFromResource("errors.login.wrongcusttype")));
			}
			//System.out.println("****** isPasswordValid:"+bValid);
			//errorTimes = processBlankName(bValid,loginID,password,loginType);
			// //然後判斷黑名單的情況
			errorTimes = 1;

			//登錄後的處理，給session中賦值
			if (bValid == false && errorTimes > 0 && errorTimes < 3) { //登錄失敗
				ActionErrors errors = new ActionErrors();
				return (forwardErrorPage(request, mapping, ResourceReader
						.getMessageFromResource("errors.login")));
			} else if (errorTimes >= 3) { //錯誤超過次數
				ActionErrors errors = new ActionErrors();
				return (forwardErrorPage(request, mapping, ResourceReader
						.getMessageFromResource("errors.login.overtimes")));
			} else { //登錄成功

				OperFormBean bean = bo.getOperInfo(loginID);
				//System.out.println("OperID:" + bean.getOperID() + "\torgid:"
				// + bean.getOrgID());
				String operStatus = bean.getStatus();
				String ipAddress = request.getRemoteAddr();
				//System.out.println("ipAddress:" + ipAddress);

				if (operStatus.equals(PortalParas.STATUS_INVALID)) {
					return (forwardErrorPage(request, mapping, "您處於禁用狀態！"));
				} else {
					UserContext userContext = new UserContext();

					userContext.setLoginID(loginID);
					userContext.setOperID(bean.getOperID());
					userContext.setOperName(bean.getOperName());
					userContext.setOrgID(bean.getOrgID());
					userContext.setRole(bo.getOperRoles(bean.getOperID()));
					userContext.setOperType(bean.getOperType());
					//add by jessie for JRJGDM
					//userContext.setAttribute(PortalParas.USER_JRJGDM,
					// this.getJRJGDM(bean.getOrgID()));
					userContext.setAttribute(PortalParas.USER_JRJGDM, this
							.getZHJLBS(bean.getOrgID()));
					HttpSession session = request.getSession(true);

					session.setAttribute(Paras.get("session"), userContext);
					if (!userContext.getOperID().equals(SysPara.ADMIN_OPERID)) {
						//						if (PCSUtil.getSysStatus().equals(
						//								SysPara.SYSSTATUS_BUSY)) {
						//							//to do alert and return login page
						//							session.invalidate();
						//							return (forwardErrorPage(request, mapping,
						// "系統處於繁忙狀態,請不要進行業務操作！"));
						//						}
					}

					//add by jessie for test get session list
					//					log.info("========user list start===========");
					//					log.info("=All user is the num
					// "+PCSSessionListener.getNum()+".=");
					//					Iterator iterator = PCSSessionListener.getAllSession();
					//					while (iterator.hasNext()) {
					//						HttpSession session1 = (HttpSession) iterator.next();
					//						UserContext user1 = null;
					//						user1 = (UserContext)
					// session1.getAttribute(Paras.get("session"));
					//						if (user1 == null) {
					//							log.info("Null session");
					//						}else{
					//							log.info("Login user:"+user1.getLoginID()+" and
					// "+user1.getLoginID());
					//						}
					//					}
					//					log.info("========user list end===========");

					String sysType = bean.getSysType();
					String sysTypeDesc = WebSelUtil.getParaDesc("system",
							sysType);

					String welComePara = Paras.get(sysTypeDesc);

					//added by hzy for various system
					try {
						initVarSysStat(userContext, sysTypeDesc);
					} catch (Exception e) {
						return (forwardErrorPage(request, mapping, e
								.getMessage()));
					}
					//updated by Guoxiaoli 2005.07.11 頁面刷新資料重複提交問題
					//return (forward(welComePara));
					return new ActionForward(welComePara, true);

					//return this.forward()

				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			return (forwardErrorPage(request, mapping, "登錄錯誤！"));
		}
	}

	private void initVarSysStat(UserContext userContext, String sysTypeDesc)
			throws Exception {
		String className = Paras.get(sysTypeDesc + "Interface");
		System.out.println(className);
		if (className.trim().length() <= 0) {
			return;
		}
		try {
			Class objClass = Class.forName(className);
			Object obj = objClass.newInstance();
			if (obj instanceof AppLoginInterface) {
				((AppLoginInterface) obj).login(userContext);
			} else {
				System.out.println("LoginAction 類型錯誤，需要 AppLoginInterface");
			}
		} catch (Exception e) {
			System.out.println("LoginAction 初始化系統UserContext錯誤：" + className);
			throw e;
		}

	}

	private void initVarSysStatus(UserContext userContext) throws Exception {

		String classNames = Paras.get("loginInteface");
		if (classNames.trim().length() <= 0) {
			return;
		}
		StringUtility stk = new StringUtility(classNames, ",");
		while (stk.hasMoreElements()) {
			String className = stk.nextToken();
			try {
				Class objClass = Class.forName(className);
				Object obj = objClass.newInstance();
				if (obj instanceof AppLoginInterface) {
					((AppLoginInterface) obj).login(userContext);
				} else {
					System.out.println("LoginAction 類型錯誤，需要 AppLoginInterface");
				}
			} catch (Exception e) {
				System.out.println("LoginAction 初始化系統UserContext錯誤："
						+ className);
			}
		}

	}

	/**
	 * 征信系統作代碼轉換，通過OrgID獲得對應用戶的金融機構代碼 與資料同步
	 * 
	 * @param orgId
	 * @return
	 */
	//	private String getJRJGDM(String orgId) {
	//		String jrjgdm = "";
	//		try {
	//			OrgBO orgbo = new OrgBO();
	//			OrgFormBean orgBean = new OrgFormBean();
	//			orgBean.setOrgID(orgId);
	//			orgBean = orgbo.retrieve(orgBean);
	//
	//			jrjgdm = orgBean.getAreaID();
	//			C_zxxt_dmdzbBO csdzBo = new C_zxxt_dmdzbBO();
	//			C_zxxt_dmdzbFormBean csdzBean = new C_zxxt_dmdzbFormBean();
	//			csdzBean.setSjybs("6101");
	//			csdzBean.setYxtdm(jrjgdm);
	//			csdzBean = csdzBo.retrieve(csdzBean);
	//			jrjgdm = csdzBean.getZxdm();
	//		} catch (SQLException e) {
	//			// TODO Auto-generated catch block
	//			e.printStackTrace();
	//		}
	//		return jrjgdm;
	//	}
	/**
	 * 征信系統作代碼轉換，通過OrgID獲得對應用戶的網點號與資料同步
	 * 
	 * @param orgId
	 * @return
	 */
	private String getZHJLBS(String orgId) {
		String zhjlbs = "";
		try {
			OrgBO orgbo = new OrgBO();
			OrgFormBean orgBean = new OrgFormBean();
			orgBean.setOrgID(orgId);
			orgBean = orgbo.retrieve(orgBean);

			zhjlbs = orgBean.getAreaID();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return zhjlbs;
	}

}
